package com.hzy.configs;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.hzy.system.domain.bo.AccountContext;
import com.hzy.system.service.IAccountService;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Optional;

/**
 * mybatis plus MetaObjectHandler 配置 insert 和 update 填充
 *
 * @author hzy
 */
@Component
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {
    private final Logger log = LoggerFactory.getLogger(MybatisPlusMetaObjectHandler.class);

    private final IAccountService accountService;

    @Lazy
    public MybatisPlusMetaObjectHandler(IAccountService accountService) {
        this.accountService = accountService;
    }

    /**
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ...." + LocalDateTime.now());
        AccountContext accountInfo = accountService.getAccountContext();
        String accountId = Optional.ofNullable(accountInfo).orElse(new AccountContext()).getId();
        this.setFieldValByName("creationTime", LocalDateTime.now(), metaObject);
        this.setFieldValByName("lastModificationTime", LocalDateTime.now(), metaObject);
        this.setFieldValByName("lastModifierUserId", accountId, metaObject);
        this.setFieldValByName("creatorUserId", accountId, metaObject);
    }

    /**
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ...." + LocalDateTime.now());
        AccountContext accountInfo = accountService.getAccountContext();
        String accountId = Optional.ofNullable(accountInfo).orElse(new AccountContext()).getId();
        this.setFieldValByName("lastModificationTime", LocalDateTime.now(), metaObject);
        this.setFieldValByName("lastModifierUserId", accountId, metaObject);
    }
}
